package com.test.book.controller;


import com.test.book.model.BookInfo;
import com.test.book.model.PageRequest;
import com.test.book.model.PageResult;
import com.test.book.model.Result;
import com.test.book.service.BookService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    BookService bookService;

    @RequestMapping("addBook")
    public String addBook(BookInfo bookInfo){
        log.info("添加图书, request: {}" , bookInfo);
        if (!StringUtils.hasLength(bookInfo.getBookName())
                || !StringUtils.hasLength(bookInfo.getAuthor())
                || bookInfo.getCount() == null
                || bookInfo.getPrice() == null
                || !StringUtils.hasLength(bookInfo.getPublish())
                || bookInfo.getStatus() == null){
            log.warn("添加图书参数不合法,request: {}",bookInfo);
            return "参数不合法";
        }
        try{
            bookService.addBook(bookInfo);
            return "";
        }catch (Exception e){
            log.error("添加图书异常,e:{}",e);
            return "添加图书发生异常";
        }

    }
    @RequestMapping("getListByPage")
    public  Result getListByPage(PageRequest pageRequest, HttpSession session){
        log.info("获取图书列表,pageRequest:{}",pageRequest);
//        if (session.getAttribute("session_user_key") == null){
//            return Result.unLogin();
//        }
        PageResult<BookInfo> pageResult = bookService.getListByPage(pageRequest);
        return Result.success(pageResult);
    }

    @RequestMapping("queryBookById")
    public BookInfo queryBookById(Integer id){
        if (id==null || id<=0){
            return new BookInfo();
        }
        return bookService.queryBookById(id);
    }

    @RequestMapping("updateBook")
    public String updateBook(BookInfo bookInfo){
        return bookService.updateBook(bookInfo);
    }

    @RequestMapping("deleteBook")
    public String deleteBook(Integer id){

        try{
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(id);
            bookInfo.setStatus(0);
            bookService.updateBook(bookInfo);
            return "";
        }catch (Exception e){
            return "删除图书发生异常";
        }
    }

    @RequestMapping("batchDeleteBook")
    public String batchDeleteBook(@RequestParam List<Integer> ids){
        log.info("批量删除图书,isa:{}",ids);
        try{
            bookService.batchDeleteBook(ids);
            return "批量删除图书成功";
        }catch (Exception e){
            log.error("删除图书异常，e:{}",e);
            return "删除图书异常";
        }
    }


}
